﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using System.Text.RegularExpressions;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS联程运价分摊
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMS_LCPriceUpdateController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMS_LCPriceUpdateController(ILogger<TMS_LCPriceUpdateDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            _logger = loggerFactory.CreateLogger<TMS_LCPriceUpdateController>();

        }

        /// <summary>
        /// TMS联程运价分摊
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostLCPriceUpdate([FromBody] TMS_LCPriceUpdateRequestDto strparm)
        {
            string  strMsg = "";
            string source_no = strparm.source_no;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMS_LCPriceUpdateResponseDto re = new TMS_LCPriceUpdateResponseDto();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            try
            {
                dic = new Dictionary<string, string>(); //查询公用dic
                dic.Add("source_no", source_no);
                DataTable dt_share = MethodHelp.GetTableInfo("TMS0115", dic,con);
                if (dt_share.Rows.Count>0)
                {
                    foreach (DataRow item in dt_share.Rows)
                    {
                        strSqlList = new List<string>();
                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("share_no", item["share_no"].ToString());
                        DataTable dt_share_d = MethodHelp.GetTableInfo("TMS0116", dic, con);
                        if (dt_share_d.Rows.Count>0)
                        {
                            decimal x_prices = 0;//打包后总价
                            decimal y_prices = 0;//打包前总价
                            decimal zk = 0;//折扣

                            List<TMS_LCPriceUpdate_Data> lc_list = new List<TMS_LCPriceUpdate_Data>();

                            //联程总价金额获取
                            dic = new Dictionary<string, string>(); //查询公用dic
                            dic.Add("price_no", dt_share_d.Rows[0]["price_no"].ToString());
                            DataTable dt_price_lc= MethodHelp.GetTableInfo("TMS0117", dic, con);
                            if (dt_price_lc.Rows.Count>0)
                            {
                                x_prices = DB.ToDecimal(dt_price_lc.Rows[0]["tax_price"].ToString());


                                //分摊明细，循环计算
                                foreach (DataRow row in dt_share_d.Rows)
                                {
                                    decimal yprice = 0;
                                    string address_begin = "";
                                    string address_end = "";
                                    string price_no = "";
                                    decimal price = 0;
                                    //运单运价计算获取
                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("waybill_no", row["waybill_no"].ToString());//查询对应物流计划
                                    DataTable fy_dt = MethodHelp.GetTableInfo("TMS0088", dic, con);//获取物流计划信息
                                    if (fy_dt.Rows.Count > 0)
                                    {
                                        foreach (DataRow row2 in fy_dt.Rows)
                                        {
                                            string price_no_d = "";

                                            dic = new Dictionary<string, string>(); //查询公用dic
                                            dic.Add("start_address", row2["shipping_city"].ToString());
                                            dic.Add("end_address", row2["delivery_city"].ToString());
                                            dic.Add("cartype_code", row2["cartype_code"].ToString());
                                            dic.Add("carrierid_code", row2["carrier_code"].ToString());
                                            DataTable dt_price = MethodHelp.GetTableInfo("TMS0112", dic, con);
                                            if (dt_price.Rows.Count > 0)
                                            {
                                                price = DB.ToDecimal(dt_price.Rows[0]["tax_price"].ToString());
                                                price_no_d = dt_price.Rows[0]["price_no"].ToString();
                                            }
                                            else
                                            {
                                                dic = new Dictionary<string, string>(); //查询公用dic
                                                dic.Add("start_address", row2["shipping_city"].ToString());
                                                dic.Add("end_address", row2["delivery_city"].ToString());
                                                dic.Add("cartypecode", row2["cartype_code"].ToString());
                                                dic.Add("carrierid_code", row2["carrier_code"].ToString());
                                                DataTable dt_price_wf = MethodHelp.GetTableInfo("TMS0113", dic, con);
                                                if (dt_price_wf.Rows.Count > 0)
                                                {
                                                    price = DB.ToDecimal(dt_price_wf.Rows[0]["tax_price"].ToString());
                                                    price_no_d = dt_price.Rows[0]["price_no"].ToString();
                                                }
                                            }
                                            if (yprice == 0)
                                            {
                                                yprice = price;
                                                address_begin = row2["shipping_city"].ToString();
                                                address_end = row2["delivery_city"].ToString();
                                                price_no = price_no_d;
                                            }
                                            else
                                            {
                                                if (yprice >= price)
                                                {
                                                    yprice = price;
                                                    address_begin = row2["shipping_city"].ToString();
                                                    address_end = row2["delivery_city"].ToString();
                                                    price_no = price_no_d;
                                                }
                                            }

                                        }
                                    }
                                    y_prices = y_prices + yprice;
                                    lc_list.Add(new TMS_LCPriceUpdate_Data
                                    {
                                        waybill_no = row["waybill_no"].ToString(),
                                        price_no= price_no,
                                        cprice= yprice
                                    }) ;
                                }

                            }

                            zk = Math.Round(x_prices/ y_prices,3);

                            foreach(var row3 in lc_list)
                            {
                                dic = new Dictionary<string, string>(); //查询公用dic
                                dic.Add("waybill_no", row3.waybill_no);
                                dic.Add("price_no", row3.price_no);
                                dic.Add("share_priceno", dt_share_d.Rows[0]["price_no"].ToString());
                                dic.Add("share_discount", zk.ToString());
                                dic.Add("finalprice", (row3.cprice* zk).ToString());
                                dic.Add("cprice", (row3.cprice * zk).ToString());
                                string strSQL = MethodHelp.GetTranSQL("TMS0118", dic,con);
                                if (strSQL != "")
                                {
                                    strSqlList.Add(strSQL.ToString());
                                }
                                else
                                {
                                    strMsg = "Parameter conversion failed";
                                }
                            }
                            if (strMsg == "")
                            {
                                if (strSqlList.Count > 0)
                                {
                                    bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                    if (A)
                                    {
                                        //回写联程单处理状态
                                        dic = new Dictionary<string, string>(); //查询公用dic
                                        dic.Add("share_no", item["share_no"].ToString());
                                        strMsg = MethodHelp.InsertIntoTable("TMS0119",dic,con);
                                    }
                                    else
                                    {
                                        strMsg = "Database update failed";
                                    }

                                }
                                else
                                {
                                    strMsg = "No insertion data present";
                                }
                            }
                        }






                    }
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
